﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using PushSharp;
using PushSharp.Android;
using PushSharp.Apple;

namespace SelfMadeMillionaire.BLL
{
    public class NotificationHelper
    {
        private NotificationHelper()
        {
            //---------------------------
            // ANDROID GCM NOTIFICATIONS
            //---------------------------
            //Configure and start Android GCM
            //IMPORTANT: The API KEY comes from your Google APIs Console App, under the API Access section, 
            //  by choosing 'Create new Server key...'
            //  You must ensure the 'Google Cloud Messaging for Android' service is enabled in your APIs Console                       
        }
        public const int MAX_LENGTH_CUSTOM_JSON = 50;

        public void SendAndroidNotification(string devices_id, string json)
        {
            //Fluent construction of an Android GCM Notification
            //IMPORTANT: For Android you MUST use your own RegistrationId here that gets generated within your Android app itself!
            using (var p = new PushBroker())
            {
                p.RegisterGcmService(new GcmPushChannelSettings(ConfigurationManager.AppSettings["GcmServerKey"]));

                p.OnChannelException += Push_OnChannelException;
                p.OnNotificationFailed += Push_OnNotificationFailed;
                p.OnServiceException += Push_OnServiceException;
                p.QueueNotification(new GcmNotification().ForDeviceRegistrationId(devices_id)
                                      .WithJson(json));
                p.StopAllServices();
            }
        }

        void Push_OnServiceException(object sender, Exception error)
        {
            File.AppendAllText("errors.txt", "\n" + DateTime.Now.ToString() + "\n" + error.Message + "\n");
        }

        void Push_OnNotificationFailed(object sender, PushSharp.Core.INotification notification, Exception error)
        {
            File.AppendAllText("errors.txt", "\n" + DateTime.Now.ToString() + "\n" + error.Message + "\n");
        }

        void Push_OnChannelException(object sender, PushSharp.Core.IPushChannel pushChannel, Exception error)
        {
            File.AppendAllText("errors.txt", "\n" + DateTime.Now.ToString() + "\n" + error.Message + "\n");
        }

        public void SendAppleNotification(string deviceToken, string message, int notifications_count, List<int> post_ids, string alertMode = "")
        {
            AppleNotification apNot = new AppleNotification()
                .ForDeviceToken(deviceToken)
                .WithAlert(message)
                .WithBadge(notifications_count)
                .WithCustomItem("new_posts", string.Join(",", post_ids));
            if (alertMode == "AlertByTone")
            {
                apNot.WithSound("sound.caf");
            }
            else
            {
                if (alertMode == "AlertByVibration")
                {
                    apNot.WithSound("vibration.caf");
                }
                else
                {
                    apNot.WithSound("silence.caf");
                }
            }


            using (var p = new PushBroker())
            {
                byte[] appleCert = File.ReadAllBytes(ConfigurationManager.AppSettings["ApplePushServiceCertificatePath"]);
                bool isProduction;
                bool.TryParse(ConfigurationManager.AppSettings["AppleIsProduction"], out isProduction);
                string password = ConfigurationManager.AppSettings["ApplePassword"];
                p.RegisterAppleService(new ApplePushChannelSettings(isProduction, appleCert, password));

                p.OnChannelException += Push_OnChannelException;
                p.OnNotificationFailed += Push_OnNotificationFailed;
                p.OnServiceException += Push_OnServiceException;
                p.OnNotificationFailed += p_OnNotificationFailed;
                p.QueueNotification(apNot);
                p.StopAllServices();
            }
        }

        public void SendAppleNotification(string deviceToken, string message)
        {
            AppleNotification apNot = new AppleNotification()
                .ForDeviceToken(deviceToken)
                .WithAlert(message);
            apNot.WithSound("sound.caf");


            using (var p = new PushBroker())
            {
                byte[] appleCert = File.ReadAllBytes(ConfigurationManager.AppSettings["ApplePushServiceCertificatePath"]);
                bool isProduction;
                bool.TryParse(ConfigurationManager.AppSettings["AppleIsProduction"], out isProduction);
                string password = ConfigurationManager.AppSettings["ApplePassword"];
                p.RegisterAppleService(new ApplePushChannelSettings(isProduction, appleCert, password));

                p.OnChannelException += Push_OnChannelException;
                p.OnNotificationFailed += Push_OnNotificationFailed;
                p.OnServiceException += Push_OnServiceException;
                p.OnNotificationFailed += p_OnNotificationFailed;
                p.QueueNotification(apNot);
                p.StopAllServices();
            }
        }

        void p_OnNotificationFailed(object sender, PushSharp.Core.INotification notification, Exception error)
        {
            File.AppendAllText("errors.txt", "\n" + DateTime.Now.ToString() + "\n" + error.Message + "\n");
        }

        private static volatile NotificationHelper instance;
        private static readonly object sync_root = new Object();

        public static NotificationHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (sync_root)
                    {
                        if (instance == null)
                            instance = new NotificationHelper();
                    }
                }

                return instance;
            }
        }
    }
}
